<template>
  <div class="">
    <div class="" v-if="!isMobile">
    <el-card v-if="contentView">
      <el-row>
        <el-col :span="4" style="margin-right: 10px">
          <el-input
            placeholder="物料编号" size="medium"
            v-model="queryInfo.materialNumber"
            clearable>
          </el-input>

        </el-col>
        <el-col :span="4" style="margin-right: 10px">
          <el-input size="medium"
                    placeholder="物料描述"
                    v-model="queryInfo.materialName"
                    clearable>
          </el-input>
        </el-col>
        <el-col :span="4" style="margin-right: 10px">
          <el-input size="medium"
                    placeholder="需求计划单号"
                    v-model="queryInfo.planNumber"
                    clearable>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="queryInfo.pushTimeStart" size="medium"
                          type="datetime"
                          placeholder="选择发布开始日期">
          </el-date-picker>
        </el-col>
        <el-col :span="4">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="queryInfo.pushTimeEnd" size="medium"
                          type="datetime"
                          placeholder="选择发布结束日期">
          </el-date-picker>
        </el-col>

        <el-col :span="2">
          <el-button   type="primary" icon="el-icon-search" @click="seacher">搜索</el-button>
        </el-col>

        <el-col :span="2" style="margin-top: 10px">
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="addImoprt">新增导入</el-button>
        </el-col>

        <el-col :span="2" style="margin-top: 10px">
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="lookeDetails">查看数据</el-button>
        </el-col>
        <el-col :span="2" style="margin-top: 10px">
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="exportPurchase">导出数据</el-button>
        </el-col>

        <el-col :span="12" style="text-align: right;">
          <div style="display: flex;justify-content:flex-end;">
            <!--          <el-button v-if="authFilter('down_materail_template')" type="primary" icon="el-icon-download" @click="downloadMaterailTemplate">下载导入模板</el-button>-->
            <!--          <el-upload   style="margin: 0 10px;" :action="importUrl+'import/uploadExcel'"-->
            <!--                        :on-success="uploadSuccessHandler"-->
            <!--                        :on-error="uploadFailHandler"-->
            <!--                        :before-upload="beforeUpload"-->
            <!--                        name="excel" :show-file-list="false" :headers="headers">-->
            <!--            <el-button v-if="authFilter('import_materail')" type="primary" icon="el-icon-download">导入</el-button>-->
            <!--          </el-upload>-->
            <!--          <el-button  v-if="authFilter('submit_procurement_order')" type="primary" icon="el-icon-plus" @click="operationView(0)">添加</el-button>-->
          </div>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table :row-style="{height: '10px'}" :cell-style="{padding:'0px'}" :data="tableData" border v-loading="loading"   >
        <el-table-column   type="index" label="序号" v-if="false" align="center" width="55"   :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="pushTime" label="发布时间"  align="center" width="100"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="planNumber" label="需求计划单号" align="center" width="100"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="standObjectNumber" label="标准对象号" align="center" width="100"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="orderNo" :show-overflow-tooltip="true" label="订单号" align="center" width="100">
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" align="center" width="100"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="materailNumber" label="物料编码" :show-overflow-tooltip="true" align="center" width="100">

        </el-table-column>
        <el-table-column prop="materailName" label="物料描述" :show-overflow-tooltip="true" align="center" width="100">
        </el-table-column>

        <!--<el-table-column prop="stockAddress" label="库存地" align="center"></el-table-column>-->

        <!--<el-table-column prop="businessType" label="业务类型" align="center"></el-table-column>-->
        <!-- <el-table-column prop="description" label="物料描述" align="center" width="200">
        </el-table-column> -->
        <!-- <el-table-column prop="planName" label="计划名称" align="center">
        </el-table-column> -->

        <!--<<el-table-column prop="projectText" label="项目文本" align="center" width="200"></el-table-column>-->
        <!--<el-table-column prop="pushTime" label="发布时间" align="center" width="150"></el-table-column>&#45;&#45;-->
        <el-table-column prop="qut" label="数量" align="center" width="70"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="singlePrice" label="单价" align="center" width="70"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="unit" label="单位" align="center" width="70"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="amount" label="金额" align="center" width="70"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="projectAmount" label="行项目金" align="center"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="unloadingAddress" :show-overflow-tooltip="true" label="卸货点" align="center"></el-table-column>
        <el-table-column prop="submitText" label="提报单元" align="center" width="100"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="workOrderNo" label="工单/网络号" align="center" width="100"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="costCenter" label="成本中心" align="center" width="100  :show-overflow-tooltip="true""></el-table-column>
        <el-table-column prop="projectText" label="项目文本" :show-overflow-tooltip="true" align="center" width="100">
        </el-table-column>

        <el-table-column  label="审核状态" align="center" width="100"   :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.status.code == 3" @click="history(scope.row)" style="color: #1c9913;cursor: pointer;">{{scope.row.status.name}}</span>
            <span v-else-if="scope.row.status.code==2" @click="history(scope.row)" style="color: #ffb547;cursor: pointer;">{{scope.row.status.name}}</span>
            <span v-else style="color: #ff4141">{{scope.row.status.name}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="100"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="creatorName" label="创建人" align="center" width="100"   :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column  label="入库状态" align="center" width="100"   :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{scope.row.inStatus.name}}</span>
          </template>
        </el-table-column>

<!--        <el-table-column label="操作" align="center">-->
<!--          <template     slot-scope="scope">-->
<!--            <el-button type="text" icon="el-icon-tickets" @click="operationView(1,scope.row)">编辑</el-button>-->
<!--            <el-button v-if="scope.row.status.code == 2" type="text" icon="el-icon-edit" @click="withdraw(scope.row)">撤回</el-button>-->
<!--            &lt;!&ndash; <el-button type="primary" icon="el-icon-delete" :loading="scope.row.loading" @click="operationView(2,scope.row)">删除</el-button> &ndash;&gt;-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <div style="float: right">合计金额:{{sum}}</div>
      <el-pagination style="text-align: center;" :disabled="loading" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[25,50]"
                     :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

    </el-card>
    <submitForm v-else :subData="subData" @closeView="closeView" @refresh="refreshTable"></submitForm>
    <historyLook :visible.sync="visible" :historyTables="historyTables"/>

    <el-dialog :visible.sync="importVisible" append-to-body width="30%">
      <p style="text-align: center;" class="map">新增导入</p>
      <el-form :model="importForm">

        <el-form-item label="导入的文件类型" prop="">
          <el-select clearable v-model="importForm.importType" filterable placeholder="导入的文件类型" @change="changeImportType">
            <el-option v-for="item in importTypes" :key="item.code" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="导入的文件" prop="fileName">
          <el-upload   style="margin: 0 10px;" :action="importUrl+'import/uploadExcel'"
                       :on-success="uploadSuccessHandler"
                       :on-error="uploadFailHandler"
                       :before-upload="beforeUpload"
                       :file-list="fileList"
                       multiple
                       name="excel" :show-file-list="true" :headers="headers">
            <el-button  type="primary" icon="el-icon-download">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传EXCEL文件</div>
          </el-upload>

        </el-form-item>

        <el-form-item>
          <el-button  type="primary" icon="el-icon-download" @click="downloadTemplate">下载导入模板</el-button>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="global-button" round type="primary" @click="importVisible = false">关闭</el-button>
        <el-button class="global-button" round type="primary" @click="submitImport">提交</el-button>
      </span>
    </el-dialog>
    </div>
    <!-- 手机 -->
    <div class="mobile-box" v-else>
      <el-row>
        <el-col :span="4"  class="mobile-seacher-box">
          <el-input
            placeholder="物料编号" size="medium"
            v-model="queryInfo.materialNumber"
            clearable>
          </el-input>

        </el-col>
        <el-col :span="4"  class="mobile-seacher-box" >
          <el-input size="medium"
                    placeholder="物料描述"
                    v-model="queryInfo.materialName"
                    clearable>
          </el-input>
        </el-col>
        <el-col :span="4"  class="mobile-seacher-box">
          <el-input size="medium"
                    placeholder="需求计划单号"
                    v-model="queryInfo.planNumber"
                    clearable>
          </el-input>
        </el-col>
        <el-col :span="4"  class="mobile-seacher-box">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="queryInfo.pushTimeStart" size="medium"
                          type="datetime"
                          placeholder="选择发布开始日期">
          </el-date-picker>
        </el-col>
        <el-col :span="4"  class="mobile-seacher-box">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="queryInfo.pushTimeEnd" size="medium"
                          type="datetime"
                          placeholder="选择发布结束日期">
          </el-date-picker>
        </el-col>
        <el-col :span="2" class="mobile-seacher-box">
          <el-button   type="primary" icon="el-icon-search" @click="seacher">搜索</el-button>
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="lookeDetails">查看数据</el-button>
        </el-col>
      </el-row>
      <div >
        <ul v-if="tableData.length" v-loading="loading">
          <li class="list-item" v-for="item in tableData" :key="item.id">
            <el-card>
              <el-col :span="24">
                <div>发布时间：{{ item.pushTime }}</div>
              </el-col>
              <el-col :span="24">
                <div>订单号：{{ item.orderNo }}</div>
              </el-col>
              <el-col :span="24">
                <div>供应商：{{ item.supplierName }}</div>
              </el-col>
              <el-col :span="24">
                <div>物料编码：{{ item.materailNumber }}</div>
              </el-col>
              <el-col :span="24">
                <div>物料描述：{{ item.materailName }}</div>
              </el-col>
              <el-col :span="24">
                <div>数量：{{ item.qut }}</div>
              </el-col>
              <el-col :span="24">
                <div>单价：{{ item.singlePrice }}</div>
              </el-col>
              <el-col :span="24">
                <div>金额：{{ item.amount }}</div>
              </el-col>
              <el-col >
                审核状态：
                  <span v-if="item.status.code == 3" @click="history(item)" style="color: #1c9913;cursor: pointer;">{{item.status.name}}</span>
                  <span v-else-if="item.status.code==2" @click="history(item)" style="color: #ffb547;cursor: pointer;">{{item.status.name}}</span>
                  <span v-else style="color: #ff4141">{{item.status.name}}</span>
              </el-col>
              <el-col :span="24" class="btn-box">
                <el-button type="primary" size="mini" @click="showDetailFun(item)">详情</el-button>
              </el-col>
            </el-card>
          </li>
          <el-pagination
            v-if="total >= queryInfo.pageSize"
            style="text-align: center; width: 90%; overflow: auto"
            :disabled="loading"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNo"
            :page-sizes="[25, 50]"
            :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </ul>
        <div v-if="!tableData.length" class="no-data">
          <img :src="require('../../assets/noData.jpg')" />
        </div>
      </div>
     <el-dialog
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        @close="closeDetailFun"
        title="详情"
        :visible.sync="showDetail"
        width="90%"
        class="detail-box"
      >
        <div>发布时间：{{detailData.pushTime}} </div>
        <div>需求计划单号：{{detailData.planNumber}} </div>
        <div>标准对象号： {{detailData.standObjectNumber}} </div>
        <div>订单号： {{detailData.orderNo}} </div>
        <div>供应商： {{detailData.supplierName}} </div>
        <div>物料编码：{{detailData.materailNumber }}</div>
        <div>物料描述：{{detailData.materailName }}</div>
        <div>数量：{{detailData.qut}}</div>
        <div>单价：{{detailData.singlePrice }}</div>
        <div>单位：{{ detailData.unit}}</div>
        <div>金额：{{detailData.amount}} </div>
        <div>行项目金：{{detailData.projectAmount}} </div>
        <div>卸货点：{{detailData.unloadingAddress}} </div>
        <div>提报单元：{{detailData.submitText}} </div>
        <div>工单/网络号：{{detailData.workOrderNo}} </div>
        <div>成本中心：{{ detailData.costCenter }}</div>
       <div>项目文本：{{ detailData.projectText }}</div>
        <div>审核状态：
          <span v-if="detailData.status">
              {{detailData.status.name}}
            </span></div>
       <div>创建时间：{{ detailData.createTime }}</div>
       <div>创建人：{{ detailData.creatorName }}</div>
       <div>入库状态：
       <span v-if="detailData.inStatus">{{ detailData.inStatus.name }}</span></div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {
  pageProcurement,
  deleteProcurement
  , downloadMaterailTemplate,
  totalProcurementAmount, exportPageProcurement
} from '@/api/purchase.js'
import { getHistoryLook, postWithdraw, myBeDone } from '@/api/user'
import submitForm from './components/submitForm.vue'
import historyLook from '@/components/historyLook'
import { mapState } from 'vuex'
import { applyImport, downloadTemplateByType } from '@/api/importApply.js'
import globalBus from '@/utils/global-bus.js'
let $this = null
export default {
  name: 'purchase',
  components: {
    submitForm,
    historyLook
  },
  computed: {
    ...mapState(['authList'])
  },
  data () {
    return {
      contentView: true,
      loading: false,
      isMobile: false,
      showForm: true,
      showDetail: false,
      placeholder: '创建人',
      queryInfo: {
        pageNo: 1,
        pageSize: 25
      },
      importUrl: this.importUrl,
      tableData: [],
      total: 0,
      subData: {
        btnId: 0,
        id: ''
      },
      visible: false,
      historyTables: [],
      headers: {
        apiKey: window.sessionStorage.getItem('token')
      },
      sum: 0,
      importVisible: false,
      importForm: {
        importType: 1,
        fileName: ''
      },
      fileList: [],
      importName: '',
      importTypes: [{ code: 1, name: '采购申请导入' }, { code: 2, name: '采购订单导入' }],
      //  手机
      detailData: {}
    }
  },
  created () {
    $this = this
    if (this.$utils.isMobile()) {
      this.isMobile = true
    }
    if (this.$route.params.id) {
      this.contentView = false
      this.subData = {
        btnId: 1,
        id: this.$route.params.id
      }
    }
    // $this.getPageProcurement()
  },
  methods: {
    // 刷新待办
    getTotal () {
      const postData = {
        pageNo: 1,
        pageSize: 25
      }
      myBeDone(postData)
        .then((res) => {
          if (res.data.code !== 200) {
            return
          }
          globalBus.$emit('setTotal', res.data.data.total)
        }).catch((err) => {})
    },
    exportPurchase () {
      exportPageProcurement($this.queryInfo).then(res => {
        $this.downloadFile(res, '采购列表')
      })
    },
    changeImportType (e) {
      $this.importTypes.forEach(v => {
        if (v.code == e) {
          $this.importName = v.name
        }
      })
    },
    downloadTemplate () {
      $this.isDown = true
      const ttt = {
        type: $this.importForm.importType
      }
      downloadTemplateByType(ttt).then(res => {
        $this.isDown = false
        $this.downloadFile(res, $this.importName + '模板')
      }).catch(err => {
        $this.isDown = false
        return $this.$message.error('导出文件错误')
      })
    },
    addImoprt () {
      this.importVisible = true
    },
    lookeDetails () {
      $this.getPageProcurement()
    },
    submitImport () {
      if (!$this.importForm.fileName) {
        $this.$message({
          type: 'error',
          message: '文件不能为空',
          showClose: true
        })
        return
      }
      $this.isDown = true
      applyImport($this.importForm).then(res => {
        if (res.headers['content-type'] && res.headers['content-type'].indexOf('multipart/form-data') >= 0) {
          $this.isDown = false
          $this.downloadFile(res, '错误信息')
          this.importVisible = false
          return
        }
        $this.isDown = false
        // console.log(res)
        if (res.headers['content-type'] && res.headers['content-type'].indexOf('application/json') >= 0) {
          $this.$message({
            type: 'error',
            message: '导入失败,请检查审批配置',
            showClose: true
          })
          return
        }
        $this.$message({
          type: 'success',
          message: '提交成功',
          showClose: true
        })
        this.importVisible = false
        // $this.$emit('refresh')

        $this.refreshTable()
      })
    },
    // 导入成功触发
    beforeUpload (file) {
      this.$loading({
        lock: true,
        text: '正在上传...',
        spinner: 'el-icon-loading'
      })
    },
    // 导入成功触发
    uploadSuccessHandler (response, file, fileList) {
      this.$loading().close()
      if (response.success) {
        $this.$message({
          type: 'success',
          message: '上传成功,请提交审批',
          showClose: true
        })
        $this.importForm.fileName = response.data.fileName
        $this.importForm.originFileName = response.data.originFileName
        $this.fileList = []
        $this.fileList.push({ name: response.data.originFileName, url: '' })
        // this.getPageProcurement()
        $this.getTotal()
      } else {
        $this.$message({
          type: 'error',
          message: response.message,
          showClose: true
        })
        $this.fileList = []
      }
    },
    uploadFailHandler () {
      this.$loading().close()
      $this.$message.error('上传失败')
    },
    downloadFile (res, name) {
      const blob = new Blob([res.data])
      const fileName = name + '.xlsx'
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    },
    authFilter (code) {
      let flag = false
      if (this.authList.length) {
        this.authList.forEach(item => {
          if (item.resourceCode == code) {
            flag = true
          }
        })
      }
      return flag
    },
    // 撤回
    withdraw (row) {
      this.$loading()
      postWithdraw({ documentId: row.id }).then(res => {
        this.$loading().close()
        const { data } = res
        if (data.code == '200') {
          this.getPageProcurement()
          this.$message.success(data.message)
        } else {
          this.$message.error(data.message)
        }
      })
    },
    // 审批历史
    history (row) {
      getHistoryLook(row.processInstanceId).then(res => {
        this.historyTables = res.data.data
        this.visible = true
      })
    },
    getPageProcurement () {
      // alert(myBeDone)
      $this.loading = true
      pageProcurement($this.queryInfo).then(res => {
        $this.loading = false
        $this.tableData = res.data.data.records
        $this.total = res.data.data.total
      }).catch(err => {
        $this.loading = false
        return $this.$message.error(err.message)
      })
      totalProcurementAmount($this.queryInfo).then(res => {
        $this.sum = res.data.data
      })
    },
    handleCurrentChange (val) {
      $this.queryInfo.pageNo = val
      $this.getPageProcurement()
    },
    handleSizeChange (size) {
      $this.queryInfo.pageSize = size
      $this.getPageProcurement()
    },
    seacher (key) {
      $this.getPageProcurement()
    },
    operationView (btnId, row) {
      if (btnId === 0) {
        $this.subData.btnId = btnId
        $this.contentView = false
      } else if (btnId === 1) {
        $this.subData.btnId = btnId
        $this.subData.id = row.id
        $this.contentView = false
      } else if (btnId === 2) {
        $this.$set(row, 'loading', true)
        $this.deleteProcurement(row)
      } else {
        return $this.$message.error('操作错误')
      }
    },
    // 删除
    deleteProcurement (row) {
      deleteProcurement(row.id).then(res => {
        $this.$set(row, 'loading', false)
        $this.getPageProcurement()
        return $this.$message.success('删除成功')
      }).catch(err => {
        $this.$set(row, 'loading', false)
        return $this.$message.error('操作错误')
      })
    },
    // 返回table
    closeView () {
      $this.contentView = true
    },
    refreshTable () {
      $this.getPageProcurement()
      $this.contentView = true
    },
    // 手机
    // 显示详情
    showDetailFun (item) {
      $this.showDetail = true
      $this.detailData = item
    },
    // 关闭详情弹窗
    closeDetailFun () {
      $this.detailData = {}
      $this.showDetail = false
    }
  }
}
</script>

<style lang="scss" scoped>
  @mixin box-width {
    width: 90%;
    margin: 10px auto;
  }
  .mobile-box {
    position: relative;
    .el-row{
      display: flex;
      flex-direction: column;
    }
    .btn-data {
      @include box-width;
    }
    .mobile-seacher-box{
      width: 90%;
      margin: 5px auto;
    }
    ul {
      padding: 0;
      & > li {
        @include box-width;
        list-style-type: none;
        .btn-box {
          text-align: right;
          margin-bottom: 10px;
        }
        .el-col {
          margin: 5px 0;
        }
      }
    }
    .no-data {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      img {
        width: 400px;
      }
    }
    .addForm {
      .el-input,
      .el-select,
      .el-textarea{
        width: 100%;
      }
      .el-form-item{
        padding: 0 20px;
        margin-bottom: 10px;
        .btn-box{
          width: 100%;
          text-align: center;
          margin: 20px 0;
          .el-button{
            width: 45%;
          }
        }
      }
    }
    .detail-box{
      overflow: auto;
      div{
        margin: 5px 0;
        font-size: 15px;
      }
    }
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: 100%;
  }
</style>
